package com.sojson.config.qps.sentinel.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.sojson.config.exception.TransException;
import com.sojson.result.Result;
import com.sojson.util.servlet.ServletUtil;

/**
 * Sentine限流工具类
 * 
 * @author liu
 * @date 2021-08-25
 */
public class SentinelUtil {

    /**
     * 返回错误信息
     * 
     * @param e
     * @throws IOException 
     */
    public static void throwException(BlockException e) throws IOException {
        throw getException(e);
    }

    /**
     * 输出数据
     * 
     * @param e
     * @throws IOException 
     */
    public static void out(BlockException e) throws IOException {
        out(ServletUtil.getHttpServletRequest(), ServletUtil.getHttpServletResponse(), e);
    }

    /**
     * 输出数据
     * 
     * @param request
     * @param response
     * @param e
     * @throws IOException 
     */
    public static void out(HttpServletRequest request, HttpServletResponse response, BlockException e)
        throws IOException {
        ServletUtil.out(request, response, Result.fail(getException(e)));
    }

    /**
     * 输出数据
     * 
     * @param e
     * @throws IOException 
     */
    public static TransException getException(BlockException e) throws IOException {
        String msg = null;

        // 不同的异常返回不同的提示语
        if (e instanceof FlowException) {
            msg = "被限流了";
        } else if (e instanceof DegradeException) {
            msg = "服务降级了";
        } else if (e instanceof ParamFlowException) {
            msg = "被限流了";
        } else if (e instanceof SystemBlockException) {
            msg = "被系统保护了";
        } else if (e instanceof AuthorityException) {
            msg = "已被拉进黑名单";
        }

        return new TransException(msg);
    }

}